package texture;

import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public abstract class BaseMetadataSectionSerializer<T> implements MetadataSectionSerializer<T> {
	protected boolean getBooleanFromJsonElement(JsonElement jsonElement, String elementName, Boolean defaultValue) {
		elementName = this.getSectionName() + "->" + elementName;

		if (jsonElement == null) {
			if (defaultValue == null) {
				throw new JsonParseException("Missing " + elementName + ": expected boolean");
			} else {
				return defaultValue.booleanValue();
			}
		} else if (!jsonElement.isJsonPrimitive()) {
			throw new JsonParseException("Invalid " + elementName + ": expected boolean, was " + jsonElement);
		} else {
			boolean flag = jsonElement.getAsBoolean();
			return flag;
		}
	}
	
	protected int getIntFromJsonElement(JsonElement jsonElement, String elementName, Integer defaultValue, int minValue, int maxValue) {
		elementName = this.getSectionName() + "->" + elementName;

		if (jsonElement == null) {
			if (defaultValue == null) {
				throw new JsonParseException("Missing " + elementName + ": expected int");
			} else {
				return defaultValue.intValue();
			}
		} else if (!jsonElement.isJsonPrimitive()) {
			throw new JsonParseException("Invalid " + elementName + ": expected int, was " + jsonElement);
		} else {
			try {
				int v = jsonElement.getAsInt();

				if (v < minValue) {
					throw new JsonParseException("Invalid " + elementName + ": expected int >= " + minValue + ", was " + v);
				} else if (v > maxValue) {
					throw new JsonParseException("Invalid " + elementName + ": expected int <= " + maxValue + ", was " + v);
				} else {
					return v;
				}
			} catch (NumberFormatException numberformatexception) {
				throw new JsonParseException("Invalid " + elementName + ": expected int, was " + jsonElement, numberformatexception);
			}
		}
	}

	protected String getStringFromJsonElement(JsonElement jsonElement, String elementName, String defaultValue, int minSize, int maxSize) {
		elementName = this.getSectionName() + "->" + elementName;

		if (jsonElement == null) {
			if (defaultValue == null) {
				throw new JsonParseException("Missing " + elementName + ": expected string");
			} else {
				return defaultValue;
			}
		} else if (!jsonElement.isJsonPrimitive()) {
			throw new JsonParseException("Invalid " + elementName + ": expected string, was " + jsonElement);
		} else {
			String v = jsonElement.getAsString();

			if (v.length() < minSize) {
				throw new JsonParseException("Invalid " + elementName + ": expected string length >= " + minSize + ", was " + v);
			} else if (v.length() > maxSize) {
				throw new JsonParseException("Invalid " + elementName + ": expected string length <= " + maxSize + ", was " + v);
			} else {
				return v;
			}
		}
	}
}
